﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;

namespace Cuckoo.TaskSchedule
{
	/// <summary>
	/// 主计时器类，每秒触发一次SecondTrigger事件，已为与任务绑定的计时器设定步进
	/// </summary>
	public class IntervalTimer : IIntervalTimer
	{
		/// <summary>
		/// 计时事件
		/// </summary>
		public event SecondTriggerHandle SecondTrigger;

		/// <summary>
		/// 触发计时事件
		/// </summary>
		public void OnSecondTrigger()
		{
			if (SecondTrigger != null)
			{
				this.nCount++;
				TotalSecond = nCount;
				if (this.nCount % Interval == 0)
				{
					if (nMaxCount != 0)
					{
						if (nCurrentCount < nMaxCount)
						{
							SecondTrigger();
							nCurrentCount++;
						}
						else
						{
							TaskStrategyFactory.CreateTaskStrategy(Task).UnRegisterTask(Task);
							return;
						}
					}
					else
					{
						SecondTrigger();
						nCurrentCount++;
					}
					
				}
			}
		}

		/// <summary>
		/// 运行计时线程
		/// </summary>
		public void Work()
		{
			nCount = 0;
			nCurrentCount = 0;
		}

		/// <summary>
		/// 计时，每秒增加1
		/// </summary>
		long nCount = 0;

		/// <summary>
		/// 当前运行次数
		/// </summary>
		long nCurrentCount = 0;

		/// <summary>
		/// 执行次数
		/// </summary>
		public int nMaxCount { get; set; }

		/// <summary>
		/// 间隔时间
		/// </summary>
		public long Interval { get; set; }

		/// <summary>
		/// 绑定到计时器上的任务
		/// </summary>
		public ITask Task { get; set; }

		/// <summary>
		/// 已运行时间
		/// </summary>
		public long TotalSecond { get; set; }
	}
}
